package chat

import (
	"cade/src/core"
	"cade/src/game/app/modules/utils"
	"cade/src/game/msg"
	"fmt"
	"strings"
	"time"
)

// ============================================================================

type gm_cmd_t []string
type gm_cmd_args_t []string

// ============================================================================

func parse_gm_cmd(text string) gm_cmd_t {
	// check indicator
	if !strings.HasPrefix(text, "/") {
		return nil
	}

	// split
	arr := strings.Split(text, " ")

	// set cmd
	arr[0] = arr[0][1:]

	return arr
}

func (self gm_cmd_t) execute(plr IPlayer) bool {
	// find handler
	h := gm_handlers[self[0]]
	if h == nil {
		return false
	}

	// res func
	res := func(text string) {
		plr.SendMsg(&msg.GS_ChatNewText{
			TextEntry: &msg.ChatTextEntry{
				Sender: plr.GetName(),
				Text:   text,
			},
		})
	}

	// execute
	h(plr, gm_cmd_args_t(self[1:]), res)
	return true
}

func (self gm_cmd_args_t) check_string(i int) string {
	L := len(self)
	if i < L {
		return self[i]
	}

	return ""
}

func (self gm_cmd_args_t) check_int32(i int) int32 {
	L := len(self)
	if i < L {
		return core.Atoi32(self[i])
	}

	return 0
}

// ============================================================================

var gm_handlers = map[string]func(IPlayer, gm_cmd_args_t, func(string)){
	"stats": func(plr IPlayer, args gm_cmd_args_t, res func(string)) {
		username := args.check_string(0)

		// find target player
		iplr := utils.FindPlayerByName(username)
		if iplr == nil {
			res("player not found")
			return
		}

		// stats
		tar := iplr.(IPlayer)
		login_ts := tar.GetLoginTs()
		online_dur := time.Since(tar.GetLoginTs()).Minutes()
		room_no := tar.GetChatroomId()

		// return
		res(fmt.Sprintf(
			"LoginTs: %s, OnlineDur: %0.2f MIN, RoomNo: %d",
			login_ts.String(), online_dur, room_no,
		))
	},

	"popular": func(plr IPlayer, args gm_cmd_args_t, res func(string)) {
		room_no := args.check_int32(0)

		// find the room
		rm := find_room(room_no)
		if rm == nil {
			res("room not found")
			return
		}

		// get hot word
		rm.Push(func() {
			w, n := rm.get_most_hot_word()
			res(fmt.Sprintf(
				"roomno: %d, hotword: %s, n: %d",
				room_no, w, n,
			))
		})
	},
}
